package com.looeyWei;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

public class HandDraw extends JPanel {

//    private boolean pressed = false;
    /**
     * 存储所有的曲线
     */
    ArrayList<Curve> curves = new ArrayList<>();

    public HandDraw(){
        MyMouseListener l = new MyMouseListener();
        this.addMouseListener(l);
        this.addMouseMotionListener(l);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // 控件的宽高
        int width = this.getWidth();
        int height = this.getHeight();
        // 填空颜色
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        // 绘制边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);

        // 两个以上的点才绘制
        for (Curve curve : curves) {
            if(curve.points.size() >= 2){
                //
                g.setColor(Color.RED);

                Point p0 = curve.points.get(0);
                for (int i = 1; i < curve.points.size(); i++) {
                    Point p1 = curve.points.get(i);
                    g.drawLine(p0.x, p0.y, p1.x, p1.y);
                    p0 = p1;
                }
            }
        }

    }
    private class MyMouseListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e) {
            super.mousePressed(e);

//            pressed = true;

            //
            Curve curve = new Curve();
            curves.add(curve);
            curve.points.add(e.getPoint());  // 记录鼠标的坐标
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            super.mouseReleased(e);

//            pressed = false;
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            super.mouseDragged(e);

//            if(pressed){
                // 当前绘制的曲线是集合里面最后一条
                Curve curve = curves.get(curves.size()-1);
                curve.points.add(e.getPoint());
                repaint();
//            }
        }
    }

    //
    private class Curve{
        private ArrayList<Point> points = new ArrayList<>();
    }
}
